<?php

/**
 * Created by PhpStorm.
 * User: CFH
 * Date: 2017/3/30
 * Time: 19:07
 */
class chart_mdl extends Model
{
    public static $table = 'mac_face_chart';
    public static $item_table = 'mac_tm_items';



    public function add_chart($id, $name,$pic,$detail_img, $itemIds, $order_index, $hot){
        $rs = $this->get_chart_one($id);
        if(empty($rs['id'])){
            $tags = $this->dbh->insert(self::$table, array(
                'name' => $name,
                'pic' => $pic,
                'detail_img' => $detail_img,
                'itemIds' => $itemIds,
                'order_index' => $order_index,
                'hot' => $hot,
                'create_time' => date('Y-m-d H:i:s')
            ));
            $rs = $this->dbh->insert_id();
        }else{
            $this->dbh->update(self::$table,
                array(
                    'name' => $name,
                    'pic' => $pic,
                    'detail_img' => $detail_img,
                    'itemIds' => $itemIds,
                    'order_index' => $order_index,
                    'hot' => $hot,
                    'create_time' => date('Y-m-d H:i:s')
                ),
                'id='.$rs['id']
            );
        }
        $rs = $this->get_chart_one($id);
        return $rs;
    }


    public function get_chart_one($id){
        $r = '';
        if(!empty($id)){
            $sql = 'SELECT *
					FROM '.self::$table.'
					WHERE id = '.$id;
            $r = $this->dbh->get_one($sql);
        }
        return $r;
    }


    public function get_chart($pageNo,$pageSize)
    {
        $sql = "SELECT COUNT(1) count FROM " .self::$table;
        $count = $this->dbh->get_one($sql);
        $total = $count["count"];
        $sql = "SELECT * 
            FROM " . self::$table ." 
            ORDER BY CASE WHEN order_index<1 THEN 9999 end, order_index
            LIMIT " .($pageNo-1)*$pageSize ." , ".$pageSize;

        /*$sql = "SELECT *
            FROM " . self::$table ."  A
            LEFT JOIN
            " . self::$item_table ."  B
            ORDER BY create_time DESC 
            LIMIT " .($pageNo-1)*$pageSize ." , ".$pageSize;*/

        $r = $this->dbh->get_all($sql);
        return array(
            'total' => $total,
            'list' => $r
        );
    }

    public function delete_chart($id){
        $result = $this->dbh->delete(self::$table," id = ".$id);
        return $result;
    }

}